<template>
  <div class="create-article">
    <h1>创建新文章</h1>
    <div class="container">
      <form class="form" ref="formRef" @submit.prevent>
        <div class="form-group">
          <label class="form-label">标题</label>
          <input type="text" class="form-control" placeholder="请输入文章标题" v-model="form.title">
        </div>
        <div class="form-group">
          <label class="form-label">简介</label>
          <input type="text" class="form-control" placeholder="请输入文章简介" v-model="form.description">
        </div>
        <div class="form-group">
          <label class="form-label">正文</label>
          <textarea class="form-control" placeholder="请输入文章正文(可以使用markdown)" v-model="form.body"></textarea>
        </div>
        <div class="form-group">
          <label class="form-label">标签</label>
          <input type="text" class="form-control" placeholder="请输入标签" v-model="tag" @keypress.enter.prevent="addTag">
        </div>
        <ul class="tags">
          <li v-for="tag in form.tagList" :key="tag">{{tag}}</li>
        </ul>
        <button class="btn" @click.self="handleSubmit">提交</button>
      </form>
    </div>
  </div>
</template>

<script lang="ts">
  interface articleFormProps {
    title: string;
    description: string;
    body: string;
    tagList: string[]
  }
  import { defineComponent, reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'
  import { postArticle } from 'src/services/article/'
  export default defineComponent({
    setup () {
      const formRef = ref<HTMLFormElement | null>(null)
      const tag = ref<string>('')
      const form = reactive<articleFormProps>({
        title: '',
        description: '',
        body: '',
        tagList: []
      })
      const addTag = () => {
        form.tagList.push(tag.value)
        tag.value = ''
      }
      const router = useRouter()
      const handleSubmit = async () => {
        const article = await postArticle(form)
        router.push({ name: 'articleDetail', params: { slug: article.slug }})
      }
      return {
        formRef,
        form,
        tag,
        addTag,
        handleSubmit
      }
    }
  })
</script>

<style lang="scss" scoped>
  .create-article {
    padding-bottom: 40px;
  }
</style>